package com.applet.system.service.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.applet.system.entity.Tree;
import org.springframework.stereotype.Service;

import com.applet.system.entity.dto.MenuDto;
import com.applet.system.mapper.MenuMapper;
import com.applet.system.service.MenuService;

import javax.annotation.Resource;


@Service
public class MenuServiceImpl implements MenuService{

	@Resource
	private MenuMapper menuMapper;

	@Override
	public List<MenuDto> getMenusAuth(Long userId) {
		List<MenuDto> menus = this.menuMapper.getMenusAuth(userId);
		List<MenuDto> formatMenus = new ArrayList<MenuDto>();
		Set<Long> ids = new HashSet<>();
		// 一级菜单
		menus.forEach( menu ->{
			if (menu.getPid() == null && !ids.contains(menu.getId())) {
				formatMenus.add(menu);
				//ids.add(menu.getId());
			}
		});
		// 二级菜单
		formatMenus.forEach( parentMenu ->{
			List<MenuDto> children = new ArrayList<MenuDto>();
			menus.forEach( menu ->{
//				if (!ids.contains(menu.getId())) {
//					ids.add(menu.getId());
					if (menu.getPid() == parentMenu.getId()) {
						children.add(menu);
//					}
				}
			});
			parentMenu.setChildren(children);
		});
		return formatMenus;
	}

	@Override
	public List<Tree> getResources() {
		return this.menuMapper.getResources();
	}

	

}
